﻿var calendars = {};
calendars.daysOfTheWeek = ['日', '一', '二', '三', '四', '五', '六'];

calendars.template =
        "<div class='clndr-controls'>" +
            "<div class='clndr-control-button previous'>" +
                "<span class='clndr-previous-button'></span>" +
            "</div>" +
            "<div class='month'><%= year %>年<%= month %></div>" +
            "<div class='clndr-control-button next'>" +
                "<span class='clndr-next-button'></span>" +
            "</div>" +
             "<div class='help'><span class='all'></span>为可选时段 <span class='none'></span>为已占用时段 </div>" +
             "<hr/>" +
        "</div>" +
       "<table class='clndr-table' border='0' cellspacing='0' cellpadding='0'>" +
            "<thead>" +
                "<tr class='header-days'>" +
                "<% for(var i = 0; i < daysOfTheWeek.length; i++) { %>" +
                    "<td class='header-day'><%= daysOfTheWeek[i] %></td>" +
                "<% } %>" +
                "</tr>" +
            "</thead>" +
            "<tbody>" +
            "<% for(var i = 0; i < numberOfRows; i++){ %>" +
                "<tr>" +
                "<% for(var j = 0; j < 7; j++){ %>" +
                "<% var d = j + i * 7; %>" +
                    "<td class='<%= days[d].classes %>'>" +
                        "<div class='day-contents'><%= days[d].day %></div>" +
                    "</td>" +
                "<% } %>" +
                "</tr>" +
            "<% } %>" +
            "</tbody>" +
        "</table>";

var _error;
function error(message, color) {
    if (!_error) _error = $('.message');
    _error.html(message);
    if (color) _error[0].style.color = color;
}

function getBookedDays(month) {
    month = month || moment().format('YYYYMM');
    $.get('/api/Venue/BookedDays',
    {
        venueId: _venueId,
        month:month
    }, function(result) {
        if (result.Code >= 0) {
            var events = [];
            result.Data.BookDays.forEach(function(item) {
                events.push({
                    date: item.Day,
                    data: item.BookType
                });
            });
            calendars.clndr1.setEvents(events);
            //将已预定的时段写入data保存
            initBooked();
        } else {
            error(result.Message);
        }
    });
};

var _selectedDays = [];
var _selectedClass = 'selected';
var _durations = ['am', 'pm', 'all'];

function initBooked() {
    $.each($('.day'), function () {
        var day = $(this);
        for (var i=0;i<_durations.length;i++) {
            if (day.hasClass(_durations[i])) {
                day.data('booked', _durations[i]);
                break;
            }
        }
    });
}

function tryBook(target) {
    var day = $(target.element);
    if (day.hasClass('past')) return;//今天之前不能预定
    var validDurations = [];
    var booked = day.data('booked') || '';
    switch(booked) {
        case '':
            validDurations = [{ id: 'am', text: '上午' }, { id: 'pm', text: '下午' }, { id: 'all', text: '全天' }];
            break;
        case 'am':
            validDurations = [{ id: 'pm', text: '下午' }];
            break;
        case 'pm':
            validDurations = [{ id: 'am', text: '上午' }];
            break;
    }
    showSelectModal(validDurations, target.date.format('YYYY-MM-DD'));
}

var _selectModal;
function showSelectModal(validDurations,day) {
    if (!validDurations || validDurations.length === 0) return;
    if (!_selectModal) _selectModal = $('#select-modal');
    var html = [];
    html.push('<li onclick="cancel(\''+day+'\')"><h2><span style="padding-left:30px">' + day + '</span><span style="float:right;color:red;font-size:15px;padding-right:10px">取消</span></h2></li>');
    validDurations.forEach(function (item) {
        html.push('<li data-id="' + item.id + '" data-day="'+day+'" onclick="select(this)">' + item.text + '</li>');
    });
    _selectModal.html(html.join(''));
    _selectModal.fadeIn();
}

function first(array,attr,value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i][attr] == value) return array[i];
    }
    return null;
}

function select(element) {
    var $self = $(element);
    var item={
        day: $self.data('day'),
        type: $self.data('id'),
        text: $self.html()
    };
    var existed = first(_selectedDays, 'day', item.day);
    if (existed == null) {
        _selectedDays.push(item);
    }
    else if (existed.type != item.type) {
        existed.type = item.type;
        existed.text = item.text;
    } else {
        _selectModal.hide();
        return;
    }
    setSelectedDayClass(item);
    showResult();
    _selectModal.hide();
}

function setSelectedDayClass(selectedDay) {
    removeSelectedDayClass(selectedDay).addClass('selected-' + selectedDay.type);
}

function removeSelectedDayClass(selectedDay) {
    var selector = '.calendar-day-' + selectedDay.day;
    var $day = $(selector);
    $day.removeClass('selected-am').removeClass('selected-pm').removeClass('selected-all');
    return $day;
}
function cancel(day) {
    var j = 0;
    for (; j < _selectedDays.length; j++) {
        if(_selectedDays[j].day==day) break;
    }
    if (j < _selectedDays.length) {
        var item = _selectedDays.splice(j, 1);
        removeSelectedDayClass(item[0]);
        showResult();
    }
    _selectModal.hide();
}

var _result;
function showResult() {
    if (!_result) _result = $('#result');
    if (_selectedDays.length === 0) {
        _result.html('<li>您还没有选择预定时段</li>');
        return;
    }
    var html = [];
    _selectedDays.forEach(function(item) {
        html.push('<li>' + item.day + ' ' + item.text + '</li>');
    });
    _result.html(html.join(''));
}

function getSelectedDays() {
    if (_selectedDays.length <= 0) return null;
    var days = [];
    _selectedDays.forEach(function(item) {
        days.push({
            Day: item.day,
            BookType: item.type
        });
    });
    return days;
}

$(function () {
    
    calendars.clndr1 = $('.cal1').clndr({
        daysOfTheWeek: calendars.daysOfTheWeek,
        template:calendars.template,
       // events: eventArray,
        clickEvents: {
            click: function (target) {
                if(target.date) tryBook(target);
            },
            today: function () {
                console.log('Cal-1 today');
            },
            nextMonth: function () {
                console.log('Cal-1 next month');
            },
            previousMonth: function () {
                console.log('Cal-1 previous month');
            },
            onMonthChange: function (event) {
                var month = parseInt(event.format('YYYYMM'));
                getBookedDays(month);
            },
            nextYear: function () {
                console.log('Cal-1 next year');
            },
            previousYear: function () {
                console.log('Cal-1 previous year');
            },
            onYearChange: function () {
                console.log('Cal-1 year changed');
            },
            nextInterval: function () {
                console.log('Cal-1 next interval');
            },
            previousInterval: function () {
                console.log('Cal-1 previous interval');
            },
            onIntervalChange: function () {
                console.log('Cal-1 interval changed');
            }
        },
        multiDayEvents: {
            singleDay: 'date',
            endDate: 'endDate',
            startDate: 'startDate'
        },
        showAdjacentMonths: false,
        adjacentDaysChangeMonth: false
    });
    getBookedDays();

    $('#submit-btn').on('click', function () {
        var errorMsg = '';
        var data = {
            VenueId: _venueId,
            BookName: $('#user').val(),
            BookPhone: $('#phone').val(),
            Reason: $('#reason').val(),
            Days:getSelectedDays()
        };
        if (data.BookName.length <= 0) {
            errorMsg += '请填写申请团体或者个人;';
        }
        if (data.BookPhone.length <= 0) {
            errorMsg += '请填写联系手机号;';
        }
        if (data.Reason.length <= 0) {
            errorMsg += '请填写申请用途;';
        }
        if (data.Days==null || data.Days.length <= 0) {
            errorMsg += '请选择预定时段;';
        }
        if (errorMsg !== '') {
            error(errorMsg);
            return;
        }
        $('#submit-btn').text('提 交 中...');
        $.ajax({
            type: 'POST',
            url: '/api/venue/book',
            data: data,
            dataType: 'json',
            success: function(result) {
                if (result.Code >= 0) {
                    $('#submit-btn').attr('disabled', 'disabled');
                    window.location.href = "/Venue/Result?from=" + result.Code;
                } else {
                    $('#submit-btn').text('提 交 申 请');
                    error(result.Message);
                }
            },
            error: function (x) {
                error('提交失败，请稍后再试');
                $('#submit-btn').text('提 交 申 请');
            }
        });
    });
});